<template>
    <div class="preview-panel">
        <div class="tree-container">
            <div class="panel-header">
                <h5>端口/设备/变量树</h5>
                <a-button
                    type="link"
                    size="small"
                    icon="reload"
                    @click="handleRefresh"
                >
                    刷新
                </a-button>
            </div>
            <a-spin :spinning="treeLoading">
                <a-tree
                    v-if="treeData.length > 0"
                    :tree-data="treeData"
                    :selected-keys="selectedTreeKeys"
                    :expanded-keys="expandedKeys"
                    @select="onTreeSelect"
                    @expand="onTreeExpand"
                >
                    <template slot="title" slot-scope="{ title, dataRef, key }">
                        <span class="tree-node-title">
                            <span class="tree-node-content">
                                <a-icon 
                                    :type="getNodeIcon(key)" 
                                    :theme="getNodeIconTheme(key)"
                                    :style="{ color: getNodeIconColor(key), marginRight: '6px' }" 
                                />
                                <span>{{ title }}</span>
                            </span>
                            <span v-if="dataRef && dataRef.type" :class="['type-tag', `type-${dataRef.type}`]">
                                {{ dataRef.type }}
                            </span>
                        </span>
                    </template>
                </a-tree>
                <a-empty v-else description="暂无数据" :image="simpleImage" />
            </a-spin>
        </div>
    </div>
</template>

<script>
import { Empty } from 'ant-design-vue'

export default {
    name: 'PreviewPanel',
    props: {
        content: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            treeData: [],
            selectedTreeKeys: [],
            expandedKeys: [],
            selectedTreeKey: null,
            treeLoading: false,
            simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
            loadedDevices: new Set() // 记录已加载变量的设备
        }
    },
    mounted() {
        this.loadDeviceTree()
    },
    methods: {
        // 加载设备树
        async loadDeviceTree() {
            this.treeLoading = true
            try {
                const res = await this.$tabManager.edge.getMqttFormatJsonDeviceTree('')
                if (res.code === 0) {
                    const data = JSON.parse(res.data)
                    const treeData = await this.convertToTreeData(data)
                    
                    // 加载所有设备的变量
                    await this.loadAllVariables(treeData)
                    
                    // 重新设置整个treeData以触发完整的重渲染
                    this.treeData = [...treeData]
                    
                    // 提取补全数据并发送给父组件
                    this.emitCompletionData()
                    
                    // 设置所有节点为展开状态
                    this.$nextTick(() => {
                        this.expandedKeys = this.getAllTreeKeys(this.treeData)
                        
                        // 默认选中第一个端口
                        if (this.treeData.length > 0) {
                            const firstPortKey = this.treeData[0].key
                            this.selectedTreeKeys = [firstPortKey]
                            this.onTreeSelect([firstPortKey])
                        }
                    })
                } else {
                    this.$message.error(res.msg || '加载设备树失败')
                }
            } catch (error) {
                console.error('加载设备树失败:', error)
                this.$message.error('加载设备树失败')
            } finally {
                this.treeLoading = false
            }
        },
        
        // 递归加载所有设备的变量
        async loadAllVariables(nodes) {
            for (const node of nodes) {
                if (node.key.startsWith('device_')) {
                    const deviceKey = node.key.replace('device_', '')
                    await this.loadVariablesForDevice(node, deviceKey)
                } else if (node.children && node.children.length > 0) {
                    await this.loadAllVariables(node.children)
                }
            }
        },
        
        // 为设备节点加载变量
        async loadVariablesForDevice(deviceNode, deviceKey) {
            if (this.loadedDevices.has(deviceKey)) return
            
            try {
                const res = await this.$tabManager.edge.getMqttFormatJsonDevicesVarJson(deviceKey)
                if (res.code === 0) {
                    const data = JSON.parse(res.data)
                    console.log('加载设备变量:', deviceKey, '数量:', data.length)
                    
                    const variables = data.map((item, index) => {
                        const varNode = {
                            title: item.name,
                            key: `var_${deviceKey}_${item.id || index}`,
                            type: item.type,
                            desc: item.desc || '-',
                            varId: item.id,
                            isLeaf: true,
                            // 使用 a-tree 的 scoped slot 渲染 title
                            scopedSlots: { title: 'title' },
                            dataRef: {
                                name: item.name,
                                type: item.type,
                                desc: item.desc,
                                varId: item.id
                            }
                        }
                        console.log('变量节点:', item.name, 'type:', item.type)
                        return varNode
                    })
                    
                    // 直接设置children
                    deviceNode.children = variables
                    this.loadedDevices.add(deviceKey)
                    
                    console.log('设备节点children数量:', deviceNode.children.length)
                }
            } catch (error) {
                console.error('加载设备变量失败:', deviceKey, error)
            }
        },
        
        // 获取所有树节点的key用于展开
        getAllTreeKeys(treeData) {
            const keys = []
            const traverse = nodes => {
                nodes.forEach(node => {
                    keys.push(node.key)
                    if (node.children && node.children.length > 0) {
                        traverse(node.children)
                    }
                })
            }
            traverse(treeData)
            return keys
        },
        
        // 转换树数据格式
        async convertToTreeData(ports, level = 1) {
            return ports.map(port => {
                const node = {
                    title: port.title,
                    key: level === 1 ? `port_${port.key}` : `device_${port.key}`,
                    // 使用 a-tree 的 scoped slot 渲染 title
                    scopedSlots: { title: 'title' },
                    children: port.children
                        ? port.children.map(child => ({
                            title: child.title,
                            key: `device_${child.key}`,
                            // 不预先设置children，让组件懒加载
                            scopedSlots: { title: 'title' },
                            dataRef: {
                                name: child.title,
                                id: child.key
                            }
                        }))
                        : [],
                    dataRef: {
                        name: port.title,
                        id: port.key
                    }
                }
                return node
            })
        },
        
        // 树节点展开/收缩处理
        onTreeExpand(expandedKeys) {
            this.expandedKeys = expandedKeys
        },
        
        // 树节点选择
        onTreeSelect(selectedKeys) {
            if (!selectedKeys.length) return
            
            this.selectedTreeKey = selectedKeys[0]
            this.selectedTreeKeys = selectedKeys
        },
        
        // 刷新按钮点击处理
        handleRefresh() {
            // 清空已加载的设备记录
            this.loadedDevices.clear()
            // 清空当前树数据和选中状态
            this.treeData = []
            this.selectedTreeKeys = []
            this.expandedKeys = []
            // 重新加载设备树
            this.loadDeviceTree()
        },
        
        // 获取节点图标
        getNodeIcon(key) {
            if (key.startsWith('port_')) {
                return 'api' // 端口图标
            } else if (key.startsWith('device_')) {
                return 'database' // 设备图标
            } else if (key.startsWith('var_')) {
                return 'tag' // 变量图标
            }
            return 'file'
        },
        
        // 获取节点图标主题
        getNodeIconTheme(key) {
            if (key.startsWith('port_')) {
                return 'filled'
            } else if (key.startsWith('device_')) {
                return 'filled'
            } else if (key.startsWith('var_')) {
                return 'outlined'
            }
            return 'outlined'
        },
        
        // 获取节点图标颜色
        getNodeIconColor(key) {
            if (key.startsWith('port_')) {
                return '#1890ff' // 蓝色 - 端口
            } else if (key.startsWith('device_')) {
                return '#52c41a' // 绿色 - 设备
            } else if (key.startsWith('var_')) {
                return '#fa8c16' // 橙色 - 变量
            }
            return '#8c8c8c'
        },
        
        // 提取补全数据并发送给父组件
        emitCompletionData() {
            const completions = []
            
            // 遍历树数据提取端口、设备、变量
            const extractNodes = nodes => {
                nodes.forEach(node => {
                    if (node.key.startsWith('port_')) {
                        // 端口节点
                        completions.push({
                            caption: node.title,
                            value: node.title,
                            meta: '端口',
                            score: 1600,
                            docHTML: `<b>${node.title}</b><br/>类型: 端口<br/><i>端口名称</i>`
                        })
                    } else if (node.key.startsWith('device_')) {
                        // 设备节点
                        completions.push({
                            caption: node.title,
                            value: node.title,
                            meta: '设备',
                            score: 1500,
                            docHTML: `<b>${node.title}</b><br/>类型: 设备<br/><i>设备名称</i>`
                        })
                    } else if (node.key.startsWith('var_')) {
                        // 变量节点
                        const type = node.dataRef?.type || node.type || 'unknown'
                        const desc = node.dataRef?.desc || node.desc || '无描述'
                        completions.push({
                            caption: node.title,
                            value: node.title,
                            meta: `变量(${type})`,
                            score: 1700, // 变量优先级最高
                            docHTML: `<b>${node.title}</b><br/>类型: ${type}<br/>描述: ${desc}`
                        })
                    }
                    
                    // 递归处理子节点
                    if (node.children && node.children.length > 0) {
                        extractNodes(node.children)
                    }
                })
            }
            
            extractNodes(this.treeData)
            
            console.log('📤 [PreviewPanel] 发送补全数据，共', completions.length, '个')
            
            // 发送给父组件
            this.$emit('update-completions', completions)
        }
        
    }
}
</script>

<style scoped lang="scss">
.preview-panel h4 {
    font-size: 14px;
    font-weight: 500;
    margin: 0 0 12px 0;
    color: #262626;
}
.preview-content {
    background: #f5f5f5;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 12px;
    max-height: 600px;
    overflow: auto;
}
.tree-container {
    background: #fff;
    border-radius: 4px;
    padding: 12px;
    min-height: 500px;
    overflow-y: auto;
}
.panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e8e8e8;
    h5 {
        font-size: 13px;
        font-weight: 500;
        margin: 0;
        color: #262626;
    }
}
::v-deep .ant-tree {
    background: transparent;
    .ant-tree-node-content-wrapper {
        &:hover {
            background-color: #f5f5f5;
        }
    }
    .ant-tree-node-selected {
        .ant-tree-node-content-wrapper {
            background-color: #e6f7ff;
        }
    }
    .ant-tree-title {
        display: inline-flex;
        align-items: center;
    }
}
.tree-node-title {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    width: 100%;
}
.tree-node-content {
    display: inline-flex;
    align-items: center;
    flex: 1;
}
.type-tag {
    display: inline-block;
    margin-left: 8px;
    padding: 2px 8px;
    font-size: 11px;
    font-weight: 600;
    border-radius: 3px;
    color: #fff;
    line-height: 1.5;
}
.type-string {
    background-color: #1890ff;
}
.type-uint,
.type-int,
.type-int16,
.type-int32,
.type-int64,
.type-uint16,
.type-uint32,
.type-uint64,
.type-float,
.type-double {
    background-color: #52c41a;
}
.type-bool {
    background-color: #fa8c16;
}
.type-byte {
    background-color: #722ed1;
}
.type-bit {
    background-color: #13c2c2;
}
.preview-content::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}
.preview-content::-webkit-scrollbar-track {
    background: #f5f5f5;
}
.preview-content::-webkit-scrollbar-thumb {
    background: #d9d9d9;
    border-radius: 3px;
}
.preview-content::-webkit-scrollbar-thumb:hover {
    background: #bfbfbf;
}
.tree-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}
.tree-container::-webkit-scrollbar-track {
    background: #fafafa;
}
.tree-container::-webkit-scrollbar-thumb {
    background: #d9d9d9;
    border-radius: 3px;
}
</style>

